<template>
  <div class="p-4 max-w-3xl mx-auto" ref="rootEl">
    <div v-for="(question, index) in forMatQuestion" :key="question.id" class="mb-6 p-4 border rounded shadow-sm">
      <div class="font-medium mb-2">{{ index + 1 }}. {{ removePrefix(question.stem) }}</div>

      <div class="space-y-2">
        <div v-for="option in question.options" :key="option" class="block">
          <div v-html="option"></div>
        </div>
      </div>
    </div>
    <span v-if="!forMatQuestion.length"> 正在生成中... </span>
  </div>
</template>

<script setup>
import { computed, ref, toRefs, onMounted, reactive, nextTick, watch } from 'vue';
import { useKatexRender } from '@/hooks/useKatexRender.ts';
import { isEmpty } from 'lodash';

const props = defineProps({
  questions: {
    type: String,
  },
});

const { questions } = toRefs(props);

const decodeHtml = str => {
  const txt = document.createElement('textarea');
  txt.innerHTML = str;
  return txt.value;
};

const forMatQuestion = computed(() => {
  let raw = questions.value;

  // 确保是字符串
  if (typeof raw !== 'string') return [];

  // 替换属性名引号：id: -> "id":
  raw = raw
    .trim()
    // 替换属性名未加引号
    .replace(/([{,]\s*)([a-zA-Z0-9_]+)\s*:/g, '$1"$2":')
    // 替换值单引号为双引号
    .replace(/:\s*'([^']*?)'/g, ': "$1"')
    // 替换数组中的单引号
    .replace(/'\s*,\s*'/g, '", "')
    .replace(/\[\s*'/g, '["')
    .replace(/'\s*\]/g, '"]')
    // ✅ 移除对象或数组末尾多余的逗号：包括 "],", "},"
    .replace(/,\s*([\]}])/g, '$1');

  try {
    const data = JSON.parse(raw);

    return data.map(v => {
      v.stem = decodeHtml(v.stem);
      v.options = v.options.map(v => decodeHtml(v));
      return v;
    });
  } catch (e) {
    console.log('raw==========> ', raw);
    console.error('❌ 无法解析 questions 字符串:', e.message);
    return [];
  }
});

function removePrefix(stem) {
  return stem.replace(/^\d+\.\s*/, '');
}

const rootEl = ref();
const { renderMath } = useKatexRender();

watch(
  () => forMatQuestion.value,
  newVal => {
    if (!isEmpty(newVal)) {
      nextTick(() => {
        if (rootEl.value) renderMath(rootEl.value);
      });
    }
  },
  { immediate: true, deep: true },
);
</script>

<style scoped lang="scss">
/* 可自定义样式 */

.font-medium {
  font-weight: bold;
}

.space-y-2 {
  padding: 10px;
  cursor: pointer;

  .block {
  }
}
</style>
